package com.dkd.service.impl;

import cn.elegent.token.dto.RefreshDTO;
import cn.elegent.token.refresh.service.TokenService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dkd.config.constant.LoginType;
import com.dkd.dao.PartnerDao;
import com.dkd.dto.UserDTO;
import com.dkd.entity.PartnerEntity;
import com.dkd.http.vo.LoginReq;
import com.dkd.http.vo.LoginResp;
import com.dkd.service.PartnerService;
import com.dkd.utils.BCrypt;
import com.google.common.base.Strings;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class PartnerServiceImpl extends ServiceImpl<PartnerDao, PartnerEntity> implements PartnerService {
	private final RedisTemplate<String, String> redisTemplate;
	
	@Autowired
	private TokenService tokenService;
	
	@Override
	public LoginResp login(LoginReq req) throws IOException {
		LoginResp resp = new LoginResp();
		resp.setSuccess(false);
		String code = redisTemplate.opsForValue().get(req.getClientToken());
		if (Strings.isNullOrEmpty(code)) {
			resp.setMsg("验证码错误");
			return resp;
		}
		if (!req.getCode().equals(code)) {
			resp.setMsg("验证码错误");
			return resp;
		}
		QueryWrapper<PartnerEntity> qw = new QueryWrapper<>();
		qw.lambda()
				.eq(PartnerEntity::getAccount, req.getAccount());
		PartnerEntity partnerEntity = this.getOne(qw);
		
		if (partnerEntity == null) {
			resp.setMsg("不存在该账户");
			return resp;
		}
		
		if (!BCrypt.checkpw(req.getPassword(), partnerEntity.getPassword())) {
			resp.setMsg("账号或密码错误");
			return resp;
		}
		
		resp.setSuccess(true);
		resp.setUserName(partnerEntity.getName());
		resp.setUserId(partnerEntity.getId());
		resp.setMsg("登录成功");
		
		
		UserDTO userDTO = new UserDTO();
		userDTO.setUserId(partnerEntity.getId() + "");
		userDTO.setMobile(partnerEntity.getMobile());
		List<String> roles = new ArrayList<>();
		roles.add(LoginType.LOGIN_PARTNER.getName());//合作商
		userDTO.setRoles(roles);
		RefreshDTO token = tokenService.createToken(userDTO); //生成token
		resp.setToken(token.getAccessToken().getToken());
		resp.setRefreshToken(token.getRefreshToken().getToken());
		resp.setTokenLifeTime(token.getAccessToken().getLifespan());
		resp.setRefreshLifeTime(token.getRefreshToken().getLifespan());
		return resp;
	}
}
